﻿using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Threading;
using Infrastructure.Events;
using Infrastructure.ViewModels;
using Microsoft.Practices.Composite.Events;

namespace DocumentListModule.Views
{
    /// <summary>
    /// Interaction logic for DocumentListView.xaml
    /// </summary>
    public partial class DocumentListView : UserControl, IDocumentListView
    {
        readonly IEventAggregator _eventAggregator;
        readonly Dispatcher dispatcher;
        /// <summary>
        /// Gets the <see cref="T:System.Windows.Threading.Dispatcher"/> this <see cref="T:System.Windows.Threading.DispatcherObject"/> is associated with.
        /// </summary>
        /// <value></value>
        /// <returns>The dispatcher.</returns>
        public new Dispatcher Dispatcher
        {
            get
            {
                return dispatcher;
            }
        }

        /// <summary>
        /// Gets or sets the model.
        /// </summary>
        /// <value>The model.</value>
        public ObservableCollection<CatalogItemViewModel> Model
        {
            get
            {
                return DataContext as ObservableCollection<CatalogItemViewModel>;
            }
            set
            {
                DataContext = value;
                booksDataGrid.ItemsSource = value;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentListView"/> class.
        /// </summary>
        /// <param name="eventAggregator">The event aggregator.</param>
        public DocumentListView(IEventAggregator eventAggregator)
        {
            InitializeComponent();

            dispatcher = Dispatcher.CurrentDispatcher;
            _eventAggregator = eventAggregator;
        }

        /// <summary>
        /// Handles the SelectionChanged event of the booksDataGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
        private void booksDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CatalogItemViewModel selectedItem = booksDataGrid.SelectedItem as CatalogItemViewModel;
            
            DocumentSelectedEvent documentSelectedEvent = _eventAggregator.GetEvent<DocumentSelectedEvent>();
            documentSelectedEvent.Publish(selectedItem);
        }
    }
}
